package com.tweetgraph.controller;

import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class AuthFilter implements Filter {

	private FilterConfig filterConfig;
	private static Set<String> userSet = new TreeSet<String>();

	static{
		userSet.add("nishant.vepachedu");
		userSet.add("darrencknight");
//		userSet.add("nishanth.uc");
		userSet.add("alexanderalton");
		userSet.add("austinmichaelcraig");
	}
	/**
	 * 
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
		
		/*
		 * Get the current user
		 */
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        
        if (user != null) {
			if(userSet.contains(user.getUserId())){
				filterChain.doFilter(request, response);
			}else{
				throw new ServletException("Not authorized to access this application!");
			}
        } else {
        	filterChain.doFilter(request, response);
//            ((HttpServletResponse)response).sendRedirect(userService.createLoginURL(((HttpServletRequest)request).getRequestURI()));
        }
        /*
         * Get the users table from DB
         */
//		Key userKey = KeyFactory.createKey("UsersTable", "AllowedUsers");
//		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//		Entity userList = null;
//		
//		try{
//			userList = datastore.get(userKey);
//		}catch(Exception e){
//			//do nothing
//		}
//		
//		if(userList == null){
//			throw new ServletException("No users configured to access this application!");
//			
//		}else{
//			Set<String> set = (Set<String>)userList.getProperty("userSet");
        

			
//		}

	}

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	public void init(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	public void destroy() {
	}

}
